#include "player.h"
#include "gameroom.h"
#include "pool.h"

Player::~Player()
{
    if (state == PLAYING) room->kick(this);
    hdlPool.erase(hdl);
    playerPool.erase(uid);
}

void Player::sleep()
{
    cout << "sleep";
}

void Player::recovery(const websocketpp::connection_hdl& h)
{
    hdlPool[h] = this;
    cout << uid << " recovery";
}
ErrorType Player::joinGame(GameRoom *room)
{
    if(state != STAYING) return ErrorType::WRONG_STATE_PLAYER;
    ErrorType e;
    isReady = false;
    e = room->addPlayer(this);
    if(e == ErrorType::SUCCESS) this->room = room;
    else return e;
    state = PLAYING;
    return ErrorType::SUCCESS;
}
/*
bool Player::joinGame(string rid)
{
    GameRoom *gr = roomPool["rid"];
    if (gr->addPlayer(this)) this->room = gr;
    else return false;
    state = PLAYING;
    return true;
}
*/
ErrorType Player::setPlayer(Json::Value& set)
{
    if (state != PLAYING) return ErrorType::WRONG_STATE_PLAYER;
    int i = set["icon"].asInt();
    if(i != static_cast<int>(icon)){
        if(!room->popValidIcon(i)) return ErrorType::WRONG_ARG;
        room->setIconStatus(icon, true);
        icon = static_cast<ICON>(i);
    }
    name = set["name"].asString();

    room->updatePlayer(uid);

    return ErrorType::SUCCESS;
}
ErrorType Player::exit(){
    if (state == PLAYING){
        room->kick(this);
        state = STAYING;
        room = nullptr;
        return ErrorType::SUCCESS;
    }
    else return ErrorType::WRONG_STATE_PLAYER;
}
ErrorType Player::ready(){
    if(state != PLAYING) return ErrorType::WRONG_STATE_PLAYER;
    if(isReady) return ErrorType::SUCCESS;
    isReady = true;

    return room->updateReadyPlayer(uid);
}
ErrorType Player::unready(){
    if(state != PLAYING) return ErrorType::WRONG_STATE_PLAYER;
    if(!isReady) return ErrorType::SUCCESS;
    isReady = false;
    
    return room->updateUnReadyPlayer(uid);
}